<?php

namespace App\Services\Admin\Sponsor;

use App\Exceptions\SponsorException;
use App\Models\Applet\Sponsor\SponsorGoodsModel;
use Exception;

class SponsorGoodsService extends BaseSponsorService
{

    /**
     * 认养商品列表
     * @param array $params
     * @return array
     * @throws Exception
     */
    public function list(array $params): array
    {
        $total = $this->getSponsorGoodsModel()->adminTotal($params);
        // 查询认养商品列表
        $sponsorGoodsList = $this->getSponsorGoodsModel()->adminList($params, [
            'id', 'category_id', 'province_id', 'city_id', 'region_id', 'name', 'price', 'cover_img', 'start_time', 'cycle', 'params', 'quantity', 'sale_quantity', 'is_recommend', 'status'
        ]);

        $provinceIds = array_column($sponsorGoodsList, 'province_id');
        $cityIds = array_column($sponsorGoodsList, 'city_id');
        $regionIds = array_column($sponsorGoodsList, 'region_id');

        $areaIds = array_merge($provinceIds, $cityIds, $regionIds);

        // 查询地区名称
        $areaList = $this->getAreaModel()->getAreaNameListByCodeList($areaIds);
        $areaListMap = array_column($areaList, 'name', 'code');

        $list = [];
        foreach ($sponsorGoodsList as $item) {
            $areaName = $this->getAreaName($areaListMap[$item['province_id']], $areaListMap[$item['city_id']], $areaListMap[$item['region_id']]);
            $list[] = [
                'id' => $item['id'],
                'areaName' => $areaName,
                'goodsName' => $item['name'],
                'price' => $item['price'] / 100,
                'quantity' => $item['quantity'],
                'residueQuantity' => $item['quantity'] - $item['sale_quantity'],
                'isRecommend' => $item['is_recommend'],
                'status' => $item['status'],
            ];
        }

        return [
            'list' => $list,
            'total' => $total,
        ];
    }

    /**
     * 认养商品详情
     * @param array $params
     * @return array
     * @throws SponsorException
     * @throws Exception
     */
    public function detail(array $params): array
    {
        // 查询认养商品详情
        $sponsorGoodsData = $this->getSponsorGoodsModel()->getItemById($params['id'], [
            'id', 'category_id', 'province_id', 'city_id', 'region_id', 'name', 'price',
            'cover_img', 'start_time', 'cycle', 'params', 'quantity', 'is_recommend', 'show_sale_quantity'
        ]);
        if (empty($sponsorGoodsData)) {
            throw new SponsorException('商品不存在', SponsorException::CODE_1001);
        }

        // 查询类型
        $categoryData = $this->getSponsorCategoryModel()->getItemById($sponsorGoodsData['category_id'], [
            'id', 'title', 'img_url'
        ]);
        if (empty($categoryData)) {
            throw new SponsorException('分类不存在', SponsorException::CODE_2002);
        }

        $areaIds = [$sponsorGoodsData['province_id'], $sponsorGoodsData['city_id'], $sponsorGoodsData['region_id']];

        // 查询地区名称
        $areaListData = $this->getAreaModel()->getAreaNameListByCodeList($areaIds);
        $areaList = [];
        foreach ($areaListData as $item) {
            $areaList[] = [
                'id' => $item['code'],
                'name' => $item['name'],
            ];
        }

        return [
            'id' => $sponsorGoodsData['id'],
            'categoryId' => $sponsorGoodsData['category_id'],
            'provinceId' => $sponsorGoodsData['province_id'],
            'cityId' => $sponsorGoodsData['city_id'],
            'regionId' => $sponsorGoodsData['region_id'],
            'name' => $sponsorGoodsData['name'],
            'price' => $sponsorGoodsData['price'] / 100,
            'coverImg' => $sponsorGoodsData['cover_img'],
            'startTime' => $sponsorGoodsData['start_time'],
            'cycle' => $sponsorGoodsData['cycle'],
            'params' => json_decode($sponsorGoodsData['params'], true) ?? [],
            'quantity' => $sponsorGoodsData['quantity'],
            'isRecommend' => $sponsorGoodsData['is_recommend'],
            'categoryInfo' => [
                'id' => $categoryData['id'],
                'title' => $categoryData['title'],
                'imgUrl' => $categoryData['img_url'],
            ],
            'showSaleQuantity' => $sponsorGoodsData['show_sale_quantity'],
            'areaList' => $areaList
        ];
    }

    /**
     * 创建认养商品
     * @return void
     * @throws Exception
     */
    public function create(array $params)
    {
        // 查询分类是否存在
        $category = $this->getSponsorCategoryModel()->getItemById($params['categoryId']);
        if (empty($category)) {
            throw new SponsorException('分类不存在', SponsorException::CODE_2002);
        }

        // 查询地区是否存在
        $areaIds = [$params['provinceId'], $params['cityId'], $params['regionId']];
        $areaList = $this->getAreaModel()->getAreaNameListByCodeList($areaIds);
        if (count($areaList) !== 3) {
            throw new SponsorException('地区不存在', SponsorException::CODE_3001);
        }

        $createData = [
            'category_id' => $params['categoryId'],
            'province_id' => $params['provinceId'],
            'city_id' => $params['cityId'],
            'region_id' => $params['regionId'],
            'name' => $params['name'],
            'price' => $params['price'] * 100,
            'cover_img' => $params['coverImg'],
            'start_time' => $params['startTime'],
            'cycle' => $params['cycle'],
            'params' => $params['params'] ? json_encode($params['params']) : '',
            'quantity' => $params['quantity'],
            'is_recommend' => $params['isRecommend'],
            'show_sale_quantity' => $params['showSaleQuantity'] ?? 0,
        ];

        $this->getSponsorGoodsModel()->addItem($createData);
    }

    /**
     * 更新认养商品
     * @param array $params
     * @return void
     * @throws Exception
     */
    public function update(array $params)
    {
        // 查询认养商品
        $sponsorGoodsData = $this->getSponsorGoodsModel()->getItemById($params['id']);
        if (empty($sponsorGoodsData)) {
            throw new SponsorException('商品不存在', SponsorException::CODE_1001);
        }

        $updateData = [];
        if (!empty($params['categoryId'])) {
            $updateData['category_id'] = $params['categoryId'];
        }
        if (!empty($params['provinceId'])) {
            $updateData['province_id'] = $params['provinceId'];
        }
        if (!empty($params['cityId'])) {
            $updateData['city_id'] = $params['cityId'];
        }
        if (!empty($params['regionId'])) {
            $updateData['region_id'] = $params['regionId'];
        }
        if (!empty($params['name'])) {
            $updateData['name'] = $params['name'];
        }
        if (isset($params['price'])) {
            $updateData['price'] = $params['price'] * 100;
        }
        if (!empty($params['coverImg'])) {
            $updateData['cover_img'] = $params['coverImg'];
        }
        if (!empty($params['startTime'])) {
            $updateData['start_time'] = $params['startTime'];
        }
        if (isset($params['cycle'])) {
            $updateData['cycle'] = $params['cycle'];
        }
        if (!empty($params['params'])) {
            $updateData['params'] = $params['params'];
        }
        if (isset($params['quantity'])) {
            $updateData['quantity'] = $params['quantity'];
        }
        if (!empty($params['isRecommend'])) {
            $updateData['is_recommend'] = $params['isRecommend'];
        }
        if (isset($params['showSaleQuantity'])) {
            $updateData['show_sale_quantity'] = $params['showSaleQuantity'];
        }

        $this->getSponsorGoodsModel()->updateItemById($params['id'], $updateData);
    }

    /**
     * 删除认养商品
     * @return void
     * @throws SponsorException
     * @throws Exception
     */
    public function delete(array $params)
    {
        // 查询认养商品
        $sponsorGoodsData = $this->getSponsorGoodsModel()->getItemById($params['id'], [
            'id', 'status'
        ]);
        if (empty($sponsorGoodsData)) {
            throw new SponsorException('商品不存在', SponsorException::CODE_1001);
        }
        if ($sponsorGoodsData['status'] == SponsorGoodsModel::STATUS_YES) {
            throw new SponsorException('已上架的商品不能删除', SponsorException::CODE_1006);
        }

        // 删除认养商品
        $this->getSponsorGoodsModel()->deleteItemById($params['id']);
    }

    /**
     * 上下架
     * @return void
     * @throws SponsorException
     * @throws Exception
     */
    public function release(array $params)
    {
        // 查询认养商品
        $sponsorGoodsData = $this->getSponsorGoodsModel()->getItemById($params['id'], [
            'id', 'status'
        ]);
        if (empty($sponsorGoodsData)) {
            throw new SponsorException('商品不存在', SponsorException::CODE_1001);
        }

        $updateData = [];
        if ($params['status'] == SponsorGoodsModel::STATUS_YES) {
            $updateData['status'] = SponsorGoodsModel::STATUS_YES;
            $updateData['listing_time'] = date('Y-m-d H:i:s');
        } else {
            $updateData['status'] = SponsorGoodsModel::STATUS_NO;
            $updateData['listing_time'] = null;
        }

        // 更新上下架
        $this->getSponsorGoodsModel()->updateItemById($params['id'], $updateData);
    }

    /**
     * 推荐/取消推荐
     * @return void
     * @throws SponsorException
     * @throws Exception
     */
    public function recommend(array $params)
    {
        // 查询认养商品
        $sponsorGoodsData = $this->getSponsorGoodsModel()->getItemById($params['id']);
        if (empty($sponsorGoodsData)) {
            throw new SponsorException('商品不存在', SponsorException::CODE_1001);
        }

        $updateData = [
            'is_recommend' => $params['status'],
        ];

        // 更新上下架
        $this->getSponsorGoodsModel()->updateItemById($params['id'], $updateData);
    }
}
